# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import youtube_dl
import time
import re
import os
import logging

logger = logging.getLogger("waitLive")
logger.setLevel(level=logging.DEBUG)

formatter = logging.Formatter(
    fmt="%(asctime)s %(name)s %(filename)s %(message)s",
    datefmt="%Y/%m/%d %X"
)

ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)


class MyLogger(object):
    def __init__(self, task_id):
        self.path = os.path.join(os.path.abspath('.'), str(task_id))
        os.mkdir(self.path)
        self.f = open(f"{self.path}/info.txt", 'w', encoding='utf-8')

    def __del__(self):
        self.f.close()

    def debug(self, msg):
        if msg.find("webpage") == -1 and msg.find("[youtube]") == -1 and msg.find("Downloading") == -1:
            self.f.writelines(msg + "\n")

        logger.debug("debug:"+str(msg)+"|")

    def warning(self, msg):
        logger.warning("warning:"+str(msg)+"|")

    def error(self, msg):
        ...

    def info(self, msg):
        logger.info("info:"+str(msg)+"|")


def second(error_str):
    """ 按秒返回等待时间 """
    patt = r'\b\d+\b'
    logger.debug(error_str)
    if error_str.find("days") != -1:
        return (int(1) * 60 - 0) * 60
    if error_str.find("hour") != -1:
        t = re.findall(patt, error_str)[-1]
        if int(t) >= 2:
            return (int(1) * 60 - 0) * 60
        else:
            return (int(t) * 60 - 0) * 60
    if error_str.find("few") != -1:
        return 35
    if error_str.find("minute") != -1:
        t = re.findall(patt, error_str)[-1]
        return (int(t) - 0) * 60


def info_file(yt_url,use_proxy:bool):

    taskId = time.time_ns()
    ytdLogger = MyLogger(taskId)
    ydl_opts = {
        'proxy': 'socks5://127.0.0.1:1080'if use_proxy else None,
        'simulate': True,
        'quiet': True,
        #'forceduration':True,
        'forceid': True,
        'forcetitle': True,
        'forcedescription': True,
        'forcethumbnail': True,
        'playlist_items': 1,
        'logger': ytdLogger,
        'noplaylist': False,
    }

    ydl = youtube_dl.YoutubeDL(ydl_opts)

    loopFlag = True

    while loopFlag:
        try:
            ydl.download([yt_url])
            loopFlag = False
        except youtube_dl.utils.DownloadError as e:
            a = e.__str__()
            waitTime = second(a)
            logger.info(f"wait {waitTime} seconds")
            time.sleep(waitTime)
            continue
    ytdLogger.f.flush()
    return taskId


if __name__ == '__main__':
    # TODO: 外部传入
    url = 'https://www.youtube.com/channel/UC0Owc36U9lOyi9Gx9Ic-4qg/live'
    # url = 'https://www.youtube.com/channel/UCeLzT-7b2PBcunJplmWtoDg/live'
    info_file(url,True)
